#!/bin/bash
# Клиент (компьютер ученика) стучится на этот скрипт через веб-сервер
# и тем самым заставляет доску (сервер) соединиться с его компьютером

set -e
set -f
set -u

# mktemp(1) does not respect umask
# https://bugzilla.altlinux.org/show_bug.cgi?id=42550
# $1: directory in which file will be created
# Returns path to file without creating it
# (theoretically vulnerabile to races)
_mktemp(){
	local rand
	while true
	do
		rand="$(set -eo pipefail && head -c 55 /dev/urandom | base64 | grep -o '[[:alnum:]]' | head -c 20 | tr -d '\n')"
		if ! test -f "$1"/"$rand" ; then
			echo "$1"/"$rand"
			break
		fi
	done
}

# $1: directory
_main_trigger_connect(){
	echo "$REMOTE_ADDR" > "$(_mktemp "$dir")"
}


# $1: HTTP_STATUS_CODE
# $2: HTTP_STATUS_DESCRIPTION
# $3: text of responce
_response_text(){
	if [ -z "$*" ]; then
		echo_err "Empty args of html_reposnse"
		exit 1
	fi
	echo "Status: $1 $2"
	#echo "Access-Control-Allow-Origin: *"
	echo "Content-Type: text/plain; charset=utf-8"
	echo -e "\n$3"
}

if [ "${SOURCED:-0}" != 1 ]; then
	readonly dir='/var/spool/doskast'
	_main_trigger_connect "$dir"
	_response_text 200 OK OK
fi
